﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Soundteller.Phone.Facade.Contracts;
using Soundteller.Visual.Model;

namespace Soundteller.Phone.Facade.Mappers
{
    public static class StoredGraphicToXnaGraphicConverter
    {
        private static readonly object _lock = new object();

        public static XnaGraphic Map(GraphicBase source)
        {
            if (source == null) return null;

            var graphic = source as StoredGraphic;
            if (graphic == null) throw new NotSupportedException();

            var xnaGraphic = new XnaGraphic
            {
                Name = graphic.Name,
                Texture = MapToTexture(graphic),
                ScreenCoordinates = new Rectangle(graphic.X, graphic.Y, graphic.Width, graphic.Height),
                SpriteTint = Color.White
            };
            
            return xnaGraphic;
        }

        private static Texture2D MapToTexture(StoredGraphic graphic)
        {
            lock (_lock)
            {
                if (CacheManager.Textures.Any(g => g.Name == graphic.Name))
                    return CacheManager.Textures.Single(g => g.Name == graphic.Name);

                var texture = GraphicsContext.Content.Load<Texture2D>(graphic.Name);
                texture.Name = graphic.Name;
                CacheManager.Textures.Add(texture);

                return texture;
            }
        }
    }
}